package com.jf.ajax.servlet;

import com.google.gson.Gson;
import com.jf.ajax.domain.User;
import com.jf.ajax.service.UserService;
import com.jf.ajax.utils.JDBCUtilsByDruid;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-09-18
 * Time:21:39
 */
@WebServlet(name = "UserCheckServlet2", urlPatterns = "/userCheckServlet2")
public class UserCheckServlet2 extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        resp.setContentType("text/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        User user = new User();
        if (username != null) {
            user = userService.getUserByUsername(username);
            if (user == null) {
                user = new User();
            }
        }
        String json = new Gson().toJson(user);
        out.println(json);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    public void destroy() {
        super.destroy();
        JDBCUtilsByDruid.close();
    }
}
